const path = require('path');
var $ = require('jquery');
const TorrentManager = require('./lib/torrent-manager').TorrentManager;
const Torrent = require('./lib/torrent').Torrent;

let torrentManager = null;

function tip(text) {
  const $msg = $('.top-tip');
  $msg.html(`<span style="color: #000099">${text}</span>`);
};

function errTip(text) {
  const $msg = $('.top-tip');
  $msg.html(`<span style="color: #ff0000">Error: ${text}</span>`);
}

function refresh() {
  location.reload();
}

/**
 *  Torrent
 */
function createTorrentItem(torrentShareInfo, filePath) {
  const fileName = path.basename(filePath);

  tip(`预备"${fileName}"`);
  let torrent, updateInterval;
  try {
    torrent = new Torrent(torrentShareInfo, filePath);
  } catch (err) {
    errTip(`错误: `, err.toString);
    throw err;
  }

  const template = `
      <tr>
          <td>${torrent.fileName}</td>
          <td>${add_suffix(torrent.fileSize)}</td>
          <td class="download-speed"></td>
          <td class="download"></td>
          <td class="upload-speed"></td>
          <td class="upload"></td>
          <td class="completeness"></td>
          <td>
              <button class="pause-btn">暂停</button>
              <button class="delete-btn">删除</button>
              <button class="close-btn">关闭</button>
          </td>
      </tr>
    `;
  const $torrentItem = $(template)
    , $pauseBtn = $torrentItem.find('.pause-btn')
    , $deleteBtn = $torrentItem.find('.delete-btn')
    , $closeBtn = $torrentItem.find('.close-btn')
    , $downloadSpeed = $torrentItem.find('.download-speed')
    , $uploadSpeed = $torrentItem.find('.upload-speed')
    , $download = $torrentItem.find('.download')
    , $upload = $torrentItem.find('.upload')
    , $completeness = $torrentItem.find('.completeness');

  torrent.once('ready', () => {
    tip(`开始下载"${fileName}"`);
    console.log(`开始下载"${fileName}"`);

    updateInterval = setInterval(() => {
      $downloadSpeed.text(add_suffix(torrent.downloadSpeed) + '/s');
      $uploadSpeed.text(add_suffix(torrent.uploadSpeed) + '/s');
      $download.text(add_suffix(torrent.download));
      $upload.text(add_suffix(torrent.upload));
      $completeness.text(Math.ceil(torrent.gotPieceCount / torrent.filePieceCount * 10000) / 100 + '%');
    }, 1000);
  });

  torrent.once('error', err => {
    errTip('错误: ', err.toString);
    clearInterval(updateInterval);
    $torrentItem.css('background-color', 'red');
  });

  torrent.once('close', () => {
    tip(`"${fileName}"文件已关闭`);
    clearInterval(updateInterval);
    $torrentItem.animateCss('fadeOut', () => {
      $torrentItem.remove();
    });
  });

  torrent.once('delete', () => {
    tip(`"${fileName}"文件已删除`);
    clearInterval(updateInterval);
    $torrentItem.animateCss('fadeOut', () => {
      $torrentItem.remove();
    });
  });

  torrent.once('done', () => {
    tip(`"${fileName}"下载完成.`);
    // clearInterval(updateInterval);
  });

  // 按钮 暂停/继续
  $pauseBtn.on('click', () => {
    if (torrent.isPaused) {
      torrent.resume();
      $pauseBtn.text('暂停');
    } else {
      torrent.pause();
      $pauseBtn.text('继续');
    }
  });

  // 按钮 删除
  $deleteBtn.on('click', () => {
    const b = confirm('删除该文件?');
    if (!b) return;
    tip(`删除"${fileName}"中...`);
    torrent.delete();
  });

  // 按钮 关闭
  $closeBtn.on('click', () => {
    torrent.close();
  });

  $('.download-list').append($torrentItem);
  $torrentItem.animateCss('fadeIn');

  try {
    torrentManager.addTorrent(torrent);
  } catch (err) {
    errTip(err.toString);
    torrent.close();
  }
}

/**
 * 添加下载按钮
 */
let newDownloadDialogFlag = false;
function openNewDownloadDialog() {
  if (newDownloadDialogFlag) return;
  createDownloadWindFlag = true;

  const template = `
    <div class="new-download-dialog">
      <button class="close-btn" style="">X</button>
      <div>
        <label>Torrent Info 文件:<input type="file"></label><br/>
        <button class="download-btn">开始下载</button>
      </div>
    </div>
  `
  const $dialog = $(template);
  $dialog.animateCss('fadeIn');

  $dialog.find('.download-btn').on('click', () => {
    const files = $dialog.find('input[type=file]')[0].files;
    if (!files.length) {
      alert('请选择torrent-info文件.');
      return;
    }
    const file = files[0];
    if (!file.name.endsWith('.torrent-info')) {
      alert('不是torrent-info文件');
      return;
    }

    const fileName = file.name.slice(0, file.name.lastIndexOf('.'))
      , downloadPath = path.join(path.dirname(file.path), fileName);

    createTorrentItem(file.path, downloadPath);
    $dialog.animateCss('fadeOut', () => {
      $dialog.remove();
      createDownloadWindFlag = false;
    });
  });

  $dialog.find('.close-btn').on('click', () => {
    $dialog.animateCss('fadeOut', () => {
      $dialog.remove();
      createDownloadWindFlag = false;
    });
  });

  $('body').append($dialog);
}

/**
 * main
 */
$(window.document).ready(function () {
  const $peerId = $('#peer_id');

  console.log('获取websocket token...');
  innerServices.webbtConfigerAPI.get({}, res => {
    torrentManager = new TorrentManager(res.data);
    torrentManager.once('ready', peerId => {
      console.log('Torrent Manger is ready.');
      $peerId.text(peerId);
      tip('');
    });
    torrentManager.on('error', err => {
      errTip(err);
    });
  });

  // 刷新前要关闭 torrentManager
  $(window).on('beforeunload', () => {
    torrentManager.close();
  });
});
